<script setup lang="ts">
import { onMounted, computed, reactive, ref } from "vue";
import type { StudentUploadDto } from "@/api/student/type";
import { ElMessage } from 'element-plus';
// 引入学生相关的小仓库
import useStudentStore from '@/store/modules/student';
let studentStore = useStudentStore();
import { parseJwt } from "@/utils/token";


let projectName = ref('');
let projectStatus = ref('');
let location = ref('');

// 计算属性用于转换 groupFinish 的值
const finishStatusMap = computed(() => {
  return {
    0: '未开始',
    1: '需求分析进行中',
    2: '概要设计进行中',
    3: '详细设计',
    4: '软件编码',
    5: '测试',
    6: '完成'
  };
});

// 辅助函数用于获取完成进度描述
const getFinishStatus = (status: number): string => {
  // @ts-ignore
  return finishStatusMap.value[status] || '未知状态';
};

// 渲染小组成员表的信息
let tableData = ref<{
  studentName: string;
  studentId: number;
  studentNumber: string;
  groupProName: string;
  groupScore: number;
  groupId: number;
  studentFinish: number; // 允许为 null
  classId: number;
  studentPosition: number;
}[]>([]);

// 判断是否为组长
const isGroupLeader = ref<boolean>(false);
// 判断是否为组长
const isFnished = ref<boolean>(false);
onMounted(async () => {
  // 显示项目相关信息
  if (studentStore.token != null) {
    let claims = parseJwt(studentStore.token);
    console.log("学生Id为：", claims.studentId);
    try {
      console.log("data:", claims.studentId);
      await studentStore.studentGetGroup(claims.studentId);

      // 判断当前用户是否为组长
      isGroupLeader.value = studentStore.groupInfo.groupLeader === studentStore.userInfo.studentName;

      projectStatus.value = getFinishStatus(studentStore.groupInfo.groupFinish);
      location.value = studentStore.groupInfo.giteeUrl;
      projectName.value = studentStore.groupInfo.groupProName;
    } catch (error) {
      // 错误已经通过 ElMessage 显示，这里可以进行其他处理
    }
  }

  // 获取组员相关信息
  console.log("token");
  await studentStore.getGroupList({
    groupId: String(studentStore.userInfo.groupId),
    page: page.currentPage,
    pageSize: page.pageSize
  });
  tableData.value = studentStore.tableGroupData;
  page.total = studentStore.total;

  if (studentStore.groupInfo.groupFinish != 0) {
    isBackButtonDisabled.value = false;
  }
  if (studentStore.groupInfo.groupFinish === 6) {
    isNextButtonDisabled.value = true;
    isFnished.value = true;
    projectStatus.value = getFinishStatus(studentStore.groupInfo.groupFinish);
    location.value = studentStore.groupInfo.giteeUrl;
    projectName.value = studentStore.groupInfo.groupProName;
    nextButtonText.value = '完成';
  }
});

// 计算属性用于过滤 studentPosition 不等于 2 的数据
const filteredTableDataNotPosition2 = computed(() => {
  return tableData.value.filter(item => item.studentPosition !== 2 && item.groupId !== -1);
});

// 修改回调函数
const handleEdit = (row: any) => {
  notificationDialogVisible.value = true; // 显示通知对话框
  selectedRow.value = row; // 保存当前行数据
};

// 分页相关
let page = reactive({ currentPage: 1, pageSize: 10, total: 10 });

const handleUpload = async (uploadRequestOptions: any) => {
  const file = uploadRequestOptions.file;
  if (studentStore.token != null) {
    let claims = parseJwt(studentStore.token);
    const data: StudentUploadDto = {
      file,
      studentId: claims.studentId
    };
    console.log("学生Id为：", data.studentId);
    try {
      console.log("data:", data);
      await studentStore.uploadGroupFile(data);
      fileUploaded.value = true; // 标记文件已成功上传
    } catch (error) {
      ElMessage.error('文件上传失败');
      // 错误已经通过 ElMessage 显示，这里可以进行其他处理
    }
  } else {
    ElMessage.error('未登录');
  }
};

// 新增：用于控制通知对话框的显示状态和通知内容
const notificationDialogVisible = ref(false);
const notificationForm = reactive({
  message: ''
});
const selectedRow = ref<any>(null); // 用于存储选中的行数据

// 发送通知的方法
const sendNotification = async () => {
  if (!notificationForm.message.trim()) {
    ElMessage.warning('请输入通知内容');
    return;
  }

  try {
    // 假设你有一个 API 来发送通知，这里只是模拟发送成功的情况
    await studentStore.sendNotification({
      studentId: selectedRow.value.studentId,
      studentNotice: notificationForm.message
    });
    ElMessage.success('通知发送成功');
    notificationDialogVisible.value = false; // 关闭对话框
    notificationForm.message = ''; // 清空表单
  } catch (error) {
    ElMessage.error('通知发送失败');
  }
};

const isNextButtonDisabled = ref(false); // 按钮是否禁用
const nextButtonText = ref('进入下一阶段'); // 按钮文本
const isBackButtonDisabled = ref(true); // 按钮是否禁用

let fileUploaded = ref(false);

// 进入下一阶段
const goNext = async () => {
  if (!fileUploaded.value) {
    ElMessage.warning('请先提交文件');
    return;
  }

  if (studentStore.token != null) {
    let claims = parseJwt(studentStore.token);
    console.log("学生Id为：", claims.studentId);
    await studentStore.groupEnterNext(claims.studentId);
    if (studentStore.groupInfo.groupFinish != 0) {
      isBackButtonDisabled.value = false;
    }
    // 如果已经是最后一个阶段，则禁用按钮并更改文本
    if (studentStore.groupInfo.groupFinish === 6) {
      projectStatus.value = getFinishStatus(studentStore.groupInfo.groupFinish);
      isNextButtonDisabled.value = true;
      isFnished.value = true;
      nextButtonText.value = '完成';
      ElMessage.success('所有阶段已完成');
    } else {
      fileUploaded.value = false; // 更新状态，表示现在需要重新提交文件
      projectStatus.value = getFinishStatus(studentStore.groupInfo.groupFinish);
      ElMessage.success('已进入下一阶段，请准备新的文件上传');
    }
  } else {
    projectStatus.value = getFinishStatus(studentStore.groupInfo.groupFinish);
    ElMessage.error('未登录');
  }
};
// 进入下一阶段
const goBack = async () => {


  if (studentStore.token != null) {
    let claims = parseJwt(studentStore.token);
    console.log("学生Id为：", claims.studentId);
    await studentStore.groupGoBack(claims.studentId);

    //如果不是最后一个阶段
    if (studentStore.groupInfo.groupFinish != 6) {
      nextButtonText.value = '进入下一阶段';
      isNextButtonDisabled.value = false;
    }
    // 如果已经是最后一个阶段，则禁用按钮并更改文本
    if (studentStore.groupInfo.groupFinish === 0) {
      projectStatus.value = getFinishStatus(studentStore.groupInfo.groupFinish);
      isBackButtonDisabled.value = true;
      ElMessage.success('已回到最初阶段');
    } else {
      isBackButtonDisabled.value = false;
      projectStatus.value = getFinishStatus(studentStore.groupInfo.groupFinish);
      ElMessage.success('返回上一阶段成功');
    }
  } else {
    projectStatus.value = getFinishStatus(studentStore.groupInfo.groupFinish);
    ElMessage.error('未登录');
  }
};
// 新增url
// 定义一个响应式变量来控制对话框的可见性
const dialogVisible = ref(false);

// 定义一个响应式对象来存储仓库地址
const repositoryForm = ref({
  url: ''
});

// 定义方法来处理表单提交
const onSubmitRepositoryUrl = async () => {
  try {
    // 获取 groupId 和仓库地址
    const groupId = studentStore.groupInfo.groupId;
    const giteeUrl = repositoryForm.value.url;

    if (!groupId || !giteeUrl) {
      console.error('Missing groupId or giteeUrl');
      return;
    }

    // 调用 studentStore 的 uploadUrl 方法
    await studentStore.uploadUrl({ groupId, giteeUrl });
    location.value = giteeUrl;
    // 关闭对话框并重置表单
    dialogVisible.value = false;
    repositoryForm.value.url = '';
  } catch (error) {
    console.error('Failed to submit repository URL:', error);
  }
};
</script>

<template>
  <el-card>
    <template #header>
      <div style="text-align: center">
        <h1>项目名:{{ projectName }}</h1>
      </div>
    </template>
    <div style="text-align: center;">
      <h2 class="fontContainer">项目阶段:{{ projectStatus }}</h2>
      <div class="mainContainer">
        <div class="fileContainer">
          <h3 class="fontContainer">仓库地址:{{ location }}</h3>
          <el-upload drag class="upload" multiple :http-request="handleUpload" :disabled="!isGroupLeader || isFnished">
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">
              拖动或者 <em>点击上传文件</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                上传文件小于50MB
              </div>
            </template>
          </el-upload>

          <div class="button-container"> <!-- 添加此 div 包裹按钮 -->
            <!-- 修改这里的按钮为打开对话框的按钮 -->
            <el-button type="primary" @click="dialogVisible = true" class="fontContainer"
              :disabled="!isGroupLeader">添加或修改仓库地址</el-button>
            <el-button type="primary" size="default" @click="goBack" class="custom-button"
              :disabled="!isGroupLeader || isBackButtonDisabled">
              返回上一阶段
            </el-button>
            <el-button type="primary" size="default" @click="goNext" class="custom-button"
              :disabled="!isGroupLeader || isNextButtonDisabled">
              {{ nextButtonText }}
            </el-button>
          </div>
        </div>
        <div class="tableContainer">
          <h2 class="fontContainer">成员完成情况</h2>
          <div>
            <el-table :data="filteredTableDataNotPosition2" border style="width: 100%">
              <el-table-column prop="studentName" label="姓名" width="180" />
              <el-table-column prop="studentNumber" label="学号" width="180" />
              <el-table-column label="阶段提交情况" width="180">
                <template #default="scope">
                  {{ getFinishStatus(scope.row.studentFinish) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="scope">
                  <el-button size="meidium" @click="handleEdit(scope.row)" :disabled="!isGroupLeader">发送通知</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <!-- 新增的通知对话框 -->
    <el-dialog v-model="notificationDialogVisible" title="发送通知" width="30%" center>
      <el-form :model="notificationForm" label-width="100px">
        <el-form-item label="通知内容">
          <el-input type="textarea" v-model="notificationForm.message" rows="4" placeholder="请输入通知内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="notificationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sendNotification">发送</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 新增的对话框 -->
    <el-dialog v-model="dialogVisible" title="仓库地址" width="30%" center>
      <el-form :model="repositoryForm" label-width="100px">
        <el-form-item label="仓库地址">
          <el-input v-model="repositoryForm.url" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmitRepositoryUrl">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped lang="scss">
.el-card {
  width: 100%;
  height: calc(100vh - 90px);

  .fontContainer {
    margin-bottom: 15px;
  }

  .custom-button {
    margin-bottom: 15px;
  }

  .mainContainer {
    display: flex;
    height: 500px;
    flex-wrap: wrap;
    flex-direction: row;

    .fileContainer {
      flex: 1;

      .upload {
        margin-right: 20px;
        width: calc(100% - 20px);
      }
    }
  }
}

@media (max-width: 100px) {
  .mainContainer {
    flex-direction: column !important;

    /* 确保优先级最高 */
    .mainContainer .fileContainer,
    .mainContainer .tableContainer {
      width: 100%;
    }
  }
}
</style>